package com.demo.webfluxdemo.handler;

import com.demo.webfluxdemo.domain.User;
import com.demo.webfluxdemo.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;

import java.util.Optional;

/**
 * @author: lipan
 * @date: 2021/9/24 19:42
 */

@Component
public class UserHandler {


    @Autowired
    UserRepository userRepository;

    /**
     * 查询
     * @param request
     * @return
     */
    public Mono<ServerResponse> getAll(ServerRequest request){

        return  ServerResponse.ok().contentType(MediaType.APPLICATION_JSON)
                .body(userRepository.findAll(), User.class);
    }

    /**
     * 新增
     * @param request
     * @return
     */
    public Mono<ServerResponse> createUser(ServerRequest request){

        Mono<User> userMono = request.bodyToMono(User.class);

        return  ServerResponse.ok().contentType(MediaType.APPLICATION_JSON)
                .body(userRepository.saveAll(userMono), User.class);
    }

    /**
     *  删除
     * @param request
     * @return
     */
    public Mono<ServerResponse> deleteUserById(ServerRequest request){


        System.out.println("1111");
         //resulful 风格的
        String id = request.pathVariable("id");

      return  userRepository.findById(id)
               .flatMap(u->userRepository.delete(u).then(ServerResponse.ok().build()))
               .switchIfEmpty(ServerResponse.notFound().build());

    }


    public Mono<ServerResponse> update(ServerRequest request){
        Mono<User> userMono = request.bodyToMono(User.class);
        Optional<User> userOptional = userMono.blockOptional();
        return   userOptional.map(u -> userRepository.findById(u.getId()).flatMap(user -> {
                    user.setAge(u.getAge());
                    user.setName(u.getName());
                    return userRepository.save(user).then(ServerResponse.ok().bodyValue("更新成功"));
                })).orElse( ServerResponse.ok().bodyValue("更新失败..."));

    }




}
